﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Web;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Daneas.Utility.Universals
{
    /// <summary>
    /// URL的操作类
    /// </summary>
    public class UrlOper
    {
        static System.Text.Encoding encoding = System.Text.Encoding.UTF8;

        #region URL的64位编码，解码
        public static string Base64Encrypt(string sourthUrl)
        {
            string eurl = HttpUtility.UrlEncode(sourthUrl);
            eurl = Convert.ToBase64String(encoding.GetBytes(eurl));
            return eurl;
        }

        public static string Base64Decrypt(string eStr)
        {
            if (!IsBase64(eStr))
            {
                return eStr;
            }
            byte[] buffer = Convert.FromBase64String(eStr);
            string sourthUrl = encoding.GetString(buffer);
            sourthUrl = HttpUtility.UrlDecode(sourthUrl);
            return sourthUrl;
        }
        /// <summary>
        /// 是否是Base64字符串
        /// </summary>
        /// <param name="eStr"></param>
        /// <returns></returns>
        public static bool IsBase64(string eStr)
        {
            if ((eStr.Length % 4) != 0)
            {
                return false;
            }
            if (!Regex.IsMatch(eStr, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
            {
                return false;
            }
            return true;
        }
        #endregion

        /// <summary>
        /// 添加URL参数
        /// </summary>
        public static string AddParam(string url, string paramName, string value)
        {
            Uri uri = new Uri(url);
            if (string.IsNullOrEmpty(uri.Query))
            {
                string eval = HttpContext.Current.Server.UrlEncode(value);
                return String.Concat(url, "?" + paramName + "=" + eval);
            }
            else
            {
                string eval = HttpContext.Current.Server.UrlEncode(value);
                return String.Concat(url, "&" + paramName + "=" + eval);
            }
        }

        /// <summary>
        /// 更新URL参数
        /// </summary>
        public static string UpdateParam(string url, string paramName, string value)
        {
            string keyWord = paramName + "=";
            int index = url.IndexOf(keyWord) + keyWord.Length;
            int index1 = url.IndexOf("&", index);
            if (index1 == -1)
            {
                url = url.Remove(index, url.Length - index);
                url = string.Concat(url, value);
                return url;
            }
            url = url.Remove(index, index1 - index);
            url = url.Insert(index, value);
            return url;
        }

        /// <summary>
        /// 分析URL所属的域
        /// </summary>
        /// <param name="fromUrl"></param>
        /// <param name="domain"></param>
        /// <param name="subDomain"></param>
        public static void GetDomain(string fromUrl, out string domain, out string subDomain)
        {
            domain = "";
            subDomain = "";
            try
            {
                if (fromUrl.IndexOf("的名片") > -1)
                {
                    subDomain = fromUrl;
                    domain = "名片";
                    return;
                }

                UriBuilder builder = new UriBuilder(fromUrl);
                fromUrl = builder.ToString();

                Uri u = new Uri(fromUrl);

                if (u.IsWellFormedOriginalString())
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";

                    }
                    else
                    {
                        string Authority = u.Authority;
                        string[] ss = u.Authority.Split('.');
                        if (ss.Length == 2)
                        {
                            Authority = "www." + Authority;
                        }
                        int index = Authority.IndexOf('.', 0);
                        domain = Authority.Substring(index + 1, Authority.Length - index - 1).Replace("comhttp", "com");
                        subDomain = Authority.Replace("comhttp", "com");
                        if (ss.Length < 2)
                        {
                            domain = "不明路径";
                            subDomain = "不明路径";
                        }
                    }
                }
                else
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";
                    }
                    else
                    {
                        subDomain = domain = "不明路径";
                    }
                }
            }
            catch
            {
                subDomain = domain = "不明路径";
            }
        }

        /// <summary>
        /// 分析 url 字符串中的参数信息
        /// </summary>
        /// <param name="url">输入的 URL</param>
        /// <param name="baseUrl">输出 URL 的基础部分</param>
        /// <param name="nvc">输出分析后得到的 (参数名,参数值) 的集合</param>
        public static void ParseUrl(string url, out string baseUrl, out NameValueCollection nvc)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            nvc = new NameValueCollection();
            baseUrl = "";

            if (url == "")
                return;

            int questionMarkIndex = url.IndexOf('?');

            if (questionMarkIndex == -1)
            {
                baseUrl = url;
                return;
            }
            baseUrl = url.Substring(0, questionMarkIndex);
            if (questionMarkIndex == url.Length - 1)
                return;
            string ps = url.Substring(questionMarkIndex + 1);

            // 开始分析参数对    
            Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
            MatchCollection mc = re.Matches(ps);

            foreach (Match m in mc)
            {
                nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
            }
        }

        /// <summary>  
        /// 保存用户上传的文件 (上传一个文件)
        /// </summary>  
        /// <param name="path">保 存路径</param>  
        public static void SaveRequestFile(string path)
        {
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                HttpContext.Current.Request.Files[0].SaveAs(path);
            }

        }

        /// <summary>
        /// 获取url参数
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns></returns>
        public static string RequestQuering(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return string.Empty;
            }

            if (HttpContext.Current.Request.QueryString[key] == null || HttpContext.Current.Request.QueryString[key].ToString() == "")
            {
                return string.Empty;
            }

            return HttpContext.Current.Request[key].ToString();
        }

        /// <summary>
        /// 获取form
        /// </summary>
        /// <param name="key">name</param>
        /// <returns></returns>
        public static string RequestForm(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return string.Empty;
            }

            if (HttpContext.Current.Request.Form[key] == null || HttpContext.Current.Request.Form[key].ToString() == "")
            {
                return string.Empty;
            }

            return HttpContext.Current.Request.Form[key];
        }

        /// <summary>  
        /// 获得当前完整Url地址  
        /// </summary>  
        /// <returns>当前完整Url地 址</returns>  
        public static string GetFullUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }

        /// <summary>  
        /// 获得当前页面客户端的IP  
        /// </summary>  
        /// <returns>当前页面客户端的 IP</returns>  
        public static string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (null == result || result == String.Empty)
            {

                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            }

            if (null == result || result == String.Empty)
            {

                result = HttpContext.Current.Request.UserHostAddress;

            }

            if (null == result || result == String.Empty)
            {

                return "0.0.0.0";

            }
            return result;

        }

        /// <summary>
        /// 获取客户端mac,大写,成功返回mac，否则返回全部
        /// </summary>
        /// <returns></returns>
        public static string GetMAC()
        {
            Process process = new Process();
            process.StartInfo.FileName = "nbtstat";
            process.StartInfo.Arguments = "-a   " + HttpContext.Current.Request.UserHostAddress;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.Close();
            int index = output.LastIndexOf("MAC Address =");
            if (index > 0)
            {
                return output.Substring(index + 14, 17).ToUpper();
            }
            else
            {
                return output;
            }
        }

        /// <summary>  
        /// 判断是否来自搜索引擎链接  
        /// </summary>  
        /// <returns>是否来自搜索引擎链 接</returns>  
        public static bool IsSearchEnginesGet()
        {
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom" };

            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();

            for (int i = 0; i < SearchEngine.Length; i++)
            {

                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                {

                    return true;

                }

            }

            return false;

        }

        /// <summary>  
        /// 返回表单或Url参数的总个数  
        /// </summary>  
        /// <returns></returns>  
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }

        /// <summary>
        /// 生成文本链接
        /// </summary>
        /// <param name="pageindex">当前页面</param>
        /// <param name="total">总记录数量</param>
        /// <returns>上一页|首页|链接们|尾页|下一页</returns>
        public static string PageLinks(int pageindex, int pagesize, int total)
        {
            if (total <= 0)
            {
                return "";
            }

            HttpRequest request = HttpContext.Current.Request;
            string url = request.Url.AbsolutePath;
            string paramLine = "";

            if (!string.IsNullOrWhiteSpace(request.QueryString.ToString().Trim()))
            {
                string[] querys = request.QueryString.ToString().Trim().Split('&');
                if (querys.Length > 0)
                {
                    foreach (string item in querys)
                    {
                        if (item.Split('=')[0] == "page")
                        {
                            continue;
                        }
                        paramLine += item + "&";
                    }
                }
            }

            url = url + "?" + paramLine;


            string page = "<div class='pagelinks'>";


            //页数
            int pagecount = Convert.ToInt32(Math.Ceiling(total * 1.00 / pagesize));

            if (pagecount > 1 && pageindex > 1)
            {
                page += "<a href='" + url + "page=" + (pageindex - 1) + "' class='prev'>上一页</a><a href='" + url + "page=1'>首页</a>";
            }

            int asc = 1;
            if (pageindex - 5 > 0)
            {
                asc = pageindex - 5;
            }
            for (int i = asc; i < pageindex; i++)
            {
                page += "<a href='" + url + "page=" + i + "'>" + i + "</a>";
            }

            page += "<a class='cur' href='" + url + "page=" + pageindex + "'>" + pageindex + "</a>"; ;

            int desc = 5;
            if (pageindex + 5 >= pagecount)
            {
                desc = pagecount - pageindex;
            }

            for (int i = 1; i < desc + 1; i++)
            {
                page += "<a href='" + url + "page=" + (pageindex + i) + "'>" + (pageindex + i) + "</a>";
            }

            if (pageindex < pagecount)
            {
                page += "<a href='" + url + "page=" + pagecount + "'>尾页</a><a href='" + url + "page=" + (pageindex + 1) + "' class='next'>下一页</a>";
            }

            page += "</div>";

            return page;
        }

        /// <summary>
        /// 获取url中的param
        /// </summary>
        /// <param name="link"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string GetUrlParam(string link, string param)
        {
            try
            {
                link = link.Substring(link.LastIndexOf("?") + 1);
                string[] paramlist = link.Split('&');

                if (paramlist != null)
                {
                    foreach (var item in paramlist)
                    {
                        if (item.Substring(0, item.LastIndexOf("=")) == param)
                        {
                            return item.Substring(item.LastIndexOf("=") + 1);
                        }
                    }
                }

                return "";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        /// </summary>
        /// <param name="sArray">需要拼接的数组</param>
        /// <returns>拼接完成以后的字符串</returns>
        public static string CreateLinkString(Dictionary<string, string> dicArray)
        {
            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            //去掉最後一個&字符
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        /// <summary>
        /// 生成page插件
        /// </summary>
        /// <param name="href">完整连接</param>
        /// <param name="queryParam">参数</param>
        /// <param name="pageindex">当前页面</param>
        /// <param name="pagesize">页面溶剂</param>
        /// <param name="total">条数</param>
        /// <returns></returns>
        public static string GetPages(string href, Dictionary<string, object> queryParam, int pageindex, int pagesize, int total)
        {
            if (pageindex <= 0 || total == 0)
            {
                return "";
            }
            int pt = Convert.ToInt32(Math.Ceiling(total * 1.00 / pagesize));

            if (pt == 1)
            {
                return "";
            }

            string queryStr = "";
            if (queryParam != null)
            {
                foreach (var item in queryParam)
                {
                    queryStr += "&" + item.Key + "=" + item.Value;
                }
            }

            string p = "<div class='pagin'>";
            p += "<div class='message'>共<i class='blue'>" + total + "</i>条记录，当前显示第&nbsp;<i class='blue'>" + pageindex + "&nbsp;</i>页</div>";
            p += "<ul class='paginList'>";
            if (pageindex > 1)
            {
                p += " <li class='paginItem'><a href='" + href + "?page=" + (pageindex - 1) + queryStr + "'  ><span class='pagepre' ><</span></a></li>";
            }

            if (total / pagesize < 5)//总页数不超过5
            {
                for (int i = 1; i <= pt; i++)
                {
                    string cl = " class='paginItem'";
                    if (i == pageindex)
                    {
                        cl = " class='paginItem current'";
                    }
                    p += "<li " + cl + " > <a  href='" + href + "?page=" + i + queryStr + "'>" + i + "</a></li>";
                }
            }
            else//总页数超过5
            {
                for (int i = (pageindex - 2) > 0 ? (pageindex - 2) : pageindex; i <= ((pageindex + 3) < pt ? (pageindex + 3) : pt); i++)
                {
                    string cl = " class='paginItem'";
                    if (i == pageindex)
                    {
                        cl = " class='paginItem current'";
                    }
                    p += "<li " + cl + " > <a  href='" + href + "?page=" + i + queryStr + "'>" + i + "</a></li>";
                }
            }

            if (pageindex < pt)
            {
                p += "<li class='paginItem'><a  href='" + href + "?page=" + (pageindex + 1) + queryStr + "'  ><span class='pagenxt'>></span></a></li>";
            }
            p += "</ul>";
            p += "</div>";
            return p;


            // <div class="pagin">
            //    <div class="message">共<i class="blue">1256</i>条记录，当前显示第&nbsp;<i class="blue">2&nbsp;</i>页</div>
            //    <ul class="paginList">
            //    <li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>
            //    <li class="paginItem"><a href="javascript:;">1</a></li>
            //    <li class="paginItem current"><a href="javascript:;">2</a></li>
            //    <li class="paginItem"><a href="javascript:;">3</a></li>
            //    <li class="paginItem"><a href="javascript:;">4</a></li>
            //    <li class="paginItem"><a href="javascript:;">5</a></li>
            //    <li class="paginItem more"><a href="javascript:;">...</a></li>
            //    <li class="paginItem"><a href="javascript:;">10</a></li>
            //    <li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>
            //    </ul>
            //</div>
        }

        /// <summary>
        /// 生成手机分页
        /// </summary>
        /// <param name="href"></param>
        /// <param name="queryParam"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static string GetWapPages(string href, Dictionary<string, object> queryParam, int pageindex, int pagesize, int total)
        {

            if (pageindex <= 0 || total == 0)
            {
                return "";
            }

            int pt = Convert.ToInt32(Math.Ceiling(total * 1.00 / pagesize));

            if (pt == 1)
            {
                return "";
            }

            string queryStr = "";
            if (queryParam != null)
            {
                foreach (var item in queryParam)
                {
                    queryStr += "&" + item.Key + "=" + item.Value;
                }
            }


            string pstr = "<div class='npagein'>";

            if (pageindex > 1)
            {
                pstr += "<a href='" + href + "?page=1" + queryStr + "' class='npa'>首页</a>";
                pstr += "<a href='" + href + "?page=" + (pageindex - 1) + queryStr + "' class='npa'>上一页</a>";
            }

            pstr += "<select id='npagein_select'><option selected='selected'>第" + pageindex + "页</option>";
            if (pt < 20)
            {
                for (int i = 1; i < 20; i++)
                {
                    pstr += "<option value='" + href + "?page=" + i + queryStr + "' >第" + i + "页</option>";
                }
            }
            if (pt > 20 && pageindex > 10)
            {
                for (int i = (pageindex - 10); i < (pageindex + 10); i++)
                {
                    pstr += "<option value='" + href + "?page=" + i + queryStr + "' >第" + i + "页</option>";
                }
            }
            if (pt > 20 && pageindex <= 10)
            {
                for (int i = 1; i < (pageindex + 10); i++)
                {
                    pstr += "<option value='" + href + "?page=" + i + queryStr + "' >第" + i + "页</option>";
                }
            }

            pstr += "</select>";

            if (pageindex < pt)
            {
                pstr += "<a href='" + href + "?page=" + (pageindex + 1) + queryStr + "' class='npa'>下一页</a>";
                pstr += "<a href='" + href + "?page=" + pt + queryStr + "' class='npa'>尾页</a>";
            }

            pstr += "</div>";

            pstr += "<script type='text/javascript'>";
            pstr += "$('#npagein_select').change(function(){location.href=$('#npagein_select option:selected').val();})";
            pstr += "</script>";

            return pstr;
        }

    }
}
